<template>
    <div class="">
        <!-- 登录弹窗 -->
        <el-dialog v-dialogDrag :visible.sync="loginDialogVisible" width="320px" :close-on-click-modal="false" :append-to-body="true" @close="resetForm('phone')">
            <svg-icon class="dialogclose" @click="close_timer()" icon-file-name="close" />
            <div class="logo">
                <img :src="logo" alt="" />
            </div>
            <!-- 盒子账号登录和扫码登录同时打开 -->
            <div v-if="ishowPhone === true && ishowScan === true">
                <div class="app-container">
                    <!-- 标签切换 -->
                    <div class="tags_box flex-hcvc">
                        <svg-icon class="weixin" :class="{ isActive: 0 == active }" @click="handelToogel(0)" icon-file-name="user" />
                        <el-divider class="dividers" direction="vertical"></el-divider>
                        <svg-icon class="weixin" :class="{ isActive: 1 == active }" @click="handelToogel(1)" icon-file-name="wechat" />
                    </div>
                    <!-- 内容部分 -->
                    <div class="con_box">
                        <div v-show="active == 0">
                            <el-form :model="phone" status-icon ref="phone" :rules="rules" class="demo-ruleForm" @submit.native.prevent>
                                <el-form-item label="" prop="phonenumber">
                                    <el-input type="text" v-model="phone.phonenumber" class="nm-skin-pretty" placeholder="请输入手机号" autocomplete="off"></el-input>
                                </el-form-item>
                                <el-form-item label="" prop="password" style="margin-bottom: 20px">
                                    <el-input
                                        type="password"
                                        v-model="phone.password"
                                        class="nm-skin-pretty"
                                        placeholder="请输入密码"
                                        autocomplete="off"
                                        @keyup.enter.native="login('phone', '节流')"
                                    ></el-input>
                                </el-form-item>
                                <el-checkbox v-model="save_password" class="ckeck">保存密码</el-checkbox>
                                <el-checkbox v-model="automatic_login" class="ckeck">自动登录</el-checkbox>
                                <el-button type="primary" @click="login('phone', '节流')" class="denglu">
                                    <span v-if="!loading">登 录</span>
                                    <span v-else>登 录 中...</span>
                                </el-button>
                                <!-- <el-button @click="resetForm('phone')">重置</el-button> -->
                                <p v-if="this.Mobilephoneswitch === true ? true : false" class="ljzhuche" @click="signuprightaway(), getIPss()">立即注册</p>
                            </el-form>
                        </div>
                        <div v-show="active == 1">
                            <div class="erweima">
                                <img :src="Wx_img ? Wx_img : ''" alt="" />
                                <p>扫描微信二维码自动注册</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 盒子账号登录打开 -->
            <div v-if="ishowPhone === true && ishowScan === false" class="con_box" style="margin-top: 50px">
                <el-form :model="phone" status-icon ref="phone" :rules="rules" class="demo-ruleForm" @submit.native.prevent>
                    <el-form-item label="" prop="phonenumber">
                        <el-input type="text" v-model="phone.phonenumber" class="nm-skin-pretty" placeholder="请输入手机号" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="" prop="password" style="margin-bottom: 20px">
                        <el-input type="password" v-model="phone.password" class="nm-skin-pretty" placeholder="请输入密码" autocomplete="off" @keyup.enter.native="login('phone', '节流')"></el-input>
                    </el-form-item>
                    <el-checkbox v-model="save_password" class="ckeck">保存密码</el-checkbox>
                    <el-checkbox v-model="automatic_login" class="ckeck">自动登录</el-checkbox>
                    <el-button type="primary" @click="login('phone', '节流')" class="denglu">
                        <span v-if="!loading">登 录</span>
                        <span v-else>登 录 中...</span>
                    </el-button>
                    <!-- <el-button @click="resetForm('phone')">重置</el-button> -->
                    <p v-if="this.Mobilephoneswitch === true ? true : false" class="ljzhuche" @click="signuprightaway(), getIPss()">立即注册</p>
                </el-form>
            </div>
            <!-- 盒子扫码登录打开 -->
            <div v-if="ishowPhone === false && ishowScan === true" class="erweima" style="margin-top: 50px">
                <img :src="Wx_img ? Wx_img : ''" alt="" />
                <p style="margin-bottom: 30px">扫描微信二维码自动注册</p>
            </div>
        </el-dialog>
        <!-- 异地登录 -->
        <RemoteLogin ref="remoteLogin"></RemoteLogin>
        <!-- 注册组件 -->
        <Register ref="register"></Register>
    </div>
</template>

<script>
import globalFunction from "@/utils/globalFunction";
import RemoteLogin from '@/components/RemoteLogin.vue';
import Register from '@/components/Register.vue'
import { logins, WX_login, getIPs, WX_polling, Mobilephoneswitchs, Memberloginoptions } from '@/api/url'
export default {
  props: {},
  created () {
    this.Mobilephoneswitchs()
    this.Memberloginoptions()
    this.phone.sn = box.m_sn;
    this.chaUserId = box_info.m_dym_channel_id
  },
  data () {
    const phonecallnumber = (rule, value, callback) => {
      const reg = /^[1][3-9][0-9]{9}$/
      if (value === '' || value === undefined || value == null) {
        callback(new Error('请输入正确的手机号'))
      } else {
        if ((!reg.test(value)) && value !== '') {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      }
    }
    return {
      pageNum: 1,
      pageSize: 100,
      loginDialogVisible: false,//默认不显示登录弹窗
      active: 0,
      timer: null,
      logo: '', // 设置LOGO
      save_password: false,//默认不选中保存密码
      automatic_login: false,//默认不选中自动登录
      Mobilephoneswitch: '',//手机注册开关
      loading: false,
      Wx_img: '',//微信登录二维码
      phone: {
        phonenumber: '',
        password: '',
        sn: '',
      },
      ishowPhone: false,//盒子显示账号登录
      ishowScan: false,//盒子显示扫码登录
      rules: {
        phonenumber: [{ validator: phonecallnumber, trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }, { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }],
      },
      chaUserId: ''
    }
  },
  mounted () {
    this.$EventBus.$on('ishow_loginDialog', (data) => {
      if (this.ishowPhone === false && this.ishowScan === true) {
        this.WX_logins()
      }
      this.loginDialogVisible = data
    })
    this.$EventBus.$on('logo_image', (data) => { this.logo = data; })
  },
  methods: {
    // 登录节流
    login: globalFunction.throttle(function (phone, str2) {
      this.$refs[phone].validate(valid => {
        if (valid) {
          this.loading = true
          try {
            logins({ phoneNumber: this.phone.phonenumber, password: this.phone.password, sn: this.phone.sn }).then((res) => {
              if (res.data.code === 200) {
                this.loading = false
                this.loginDialogVisible = false
                this.$store.commit('setUser', res.data)
                window.localStorage.setItem('token', JSON.stringify(res.data.token))
                this.$message({ message: '登录成功,欢迎回来', type: 'success', center: true })
                this.handelToogel(0)
                this.$EventBus.$emit('callTopGetInfos', 1)//!调用回去用户信息的gitInfo方法
                this.$EventBus.$emit('openProfileAuths', 1)//!查询是否绑定微信和实名认证
              } else if (res.data.code === 500 && res.data.error === 1) {
                this.loading = false
                this.$refs.remoteLogin.openRemoyeLogin()//打开异地登录
                this.$refs.remoteLogin.account_phonenumber = res.data.phonenumber//异地登录手机号码
                this.$refs.remoteLogin.phoneNumber = this.phone.phonenumber
                this.loginDialogVisible = false
              } else {
                this.$message({ message: res.data.msg, type: 'error', center: true })
                this.loading = false
              }
            })
          } catch (error) {
            console.log(error)
          }
        }
      })
    }, 1000),
    resetForm (formName) {
      if (this.ishowPhone === false && this.ishowScan === true) { } else { this.$refs[formName].resetFields(); }
    },
    close_timer () {
      this.loginDialogVisible = false
      window.clearInterval(this.timer)
      this.active = '0'
    },
    //立即注册
    signuprightaway () {
      this.loginDialogVisible = false
      this.$refs.register.registerDialog = true
      this.$refs.register.getCode()
    },
    //获取IP使用情况 
    async getIPss () {
      try {
        const res = await getIPs()
        if (res.data.code === 200) {
          this.$refs.register.number = res.data.status
        }
      } catch (error) {
        console.log(error);
      }

    },
    // 如果是扫码登入界面，就调用WX_logins()
    handelToogel (index) {
      this.active = index;
      if (this.active === 1) {
        this.Wx_img = ''
        this.WX_logins()
      } else {
        window.clearInterval(this.timer)
      }
    },
    // 获取用户登录状态（轮询）
    async polling (a) {
      try {
        const res = await WX_polling(a)
        if (res.data.code === 200 && res.data.error === 0) {
          this.$message({ message: '登录成功,欢迎回来', type: 'success', center: true })
          this.$store.commit('setUser', res.data)
          window.localStorage.setItem('token', JSON.stringify(res.data.token))
          this.$EventBus.$emit('callTopGetInfos', 1)//!调用首页的gitInfo方法
          this.$EventBus.$emit('openProfileAuths', 1)//!查询是否绑定微信和实名认证
          this.active = '0'
          this.loginDialogVisible = false
          window.clearInterval(this.timer)
        }
        else if (res.data.error === 6) {
          window.clearInterval(this.timer)
          this.$message({ message: '您登陆的账户已被停用!', type: 'warning', center: true })
        } else if (res.data.error === -7) {
          window.clearInterval(this.timer)
          this.$message({ message: res.data.msg, type: 'warning', center: true })
        } else if (res.data.code === 200) {
          this.$message({ message: '登录成功,欢迎回来', type: 'success', center: true })
          this.$store.commit('setUser', res.data)
          window.localStorage.setItem('token', JSON.stringify(res.data.token))
          this.$EventBus.$emit('callTopGetInfos', 1)//!调用首页的gitInfo方法
          this.$EventBus.$emit('openProfileAuths', 1)//!查询是否绑定微信和实名认证
          this.active = '0'
          this.loginDialogVisible = false
          window.clearInterval(this.timer)
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 获取微信自动注册二维码
    async WX_logins () {
      try {
        if (this.chaUserId !== 0 && this.chaUserId !== undefined && this.chaUserId !== 'undefined' && this.chaUserId !== '') {
          const res = await WX_login({ sn: this.phone.sn, chaUserId: this.chaUserId })
          if (res.data.code === 200) {
            this.Wx_img = 'data:image/gif;base64,' + res.data.data.image_src
            this.timer = setInterval(() => {
              this.polling(res.data.data.scene_str)
            }, 2000)
          } else {
            this.$message({ message: '二维码异常，请稍后再试', type: 'error', center: true })
            this.loginDialogVisible = false
          }
        } else {
          const res = await WX_login({ sn: this.phone.sn })
          if (res.data.code === 200) {
            this.Wx_img = 'data:image/gif;base64,' + res.data.data.image_src
            this.timer = setInterval(() => {
              this.polling(res.data.data.scene_str)
            }, 2000)
          } else {
            this.$message({ message: '二维码异常，请稍后再试', type: 'error', center: true })
            this.loginDialogVisible = false
          }
        }
      } catch (err) {
        this.$message({ message: '二维码异常，请稍后再试', type: 'error', center: true })
        this.loginDialogVisible = false
      }
    },
    // 手机注册开关
    async Mobilephoneswitchs () {
      const res = await Mobilephoneswitchs()
      if (res.data.code === 200) {
        this.Mobilephoneswitch = res.data.switch
      }
    },
    // 盒子的登录方式
    async Memberloginoptions () {
      const res = await Memberloginoptions()
      if (res.data.code === 200) {
        this.ishowPhone = res.data.phone
        this.ishowScan = res.data.scan
      }
    },
  },
  computed: {},
  watch: {},
  components: { RemoteLogin, Register },
  beforeDestroy () {//移除监听事件
    this.$EventBus.$off("ishow_loginDialog")
    this.$EventBus.$off("logo_image")
  },
}
</script>

<style scoped lang='less'>
/deep/ .el-dialog__header {
    display: none;
}
/deep/ .el-dialog__body {
    height: 440px !important;
    padding: 15px 53px !important;
    border: 1.5px solid #b4875c;
    background: url('@/assets/dialogImg/loginbg.png');
}
.dialogclose {
    position: relative;
    top: -2px;
    left: 233px;
    color: #fff;
    font-size: 19px;
    z-index: 9999;
    cursor: pointer;
    &:hover {
        color: red;
    }
}
.logo {
    width: 100px;
    height: 50px;
    margin: 0 auto;
}
// 登录界面样式
.app-container {
    margin-top: 30px;
}
.tags_box {
    .weixin {
        font-size: 31px;
        color: #969696;
        &:hover {
            color: #ffd48b;
        }
    }
    .dividers {
        height: 23px;
        margin: 0 18px;
        color: #ffebd4;
    }
    .isActive {
        color: #ffb331;
    }
}
.con_box {
    margin-top: 20px;
    height: 252px;
}
.erweima {
    width: 168px;
    margin: 0 auto;
    img {
        width: 172px;
        height: 172px;
        border: 2px solid #ae8d6a;
    }
    p {
        margin-top: 30px;
        font-size: 12px;
        font-family: '微软雅黑';
        font-weight: 400;
        text-align: center;
        color: #f1e4c8;
    }
}
.ckeck {
    font-size: 12px;
    font-family: '微软雅黑';
    color: #ffb331;
    &:hover {
        color: #ffd48b;
    }
}
/deep/.el-checkbox__inner {
    top: -2px;
    border: 1px solid #ffb331;
    border-radius: 2px;
    background: rgba(0, 0, 0, 0);
}
/deep/.el-checkbox__inner:hover {
    border-color: #ffd48b;
}

/deep/.el-checkbox__input.is-checked + .el-checkbox__label {
    color: #ffd48b !important;
}
/deep/.el-checkbox__input.is-checked .el-checkbox__inner {
    border: 1px solid #ffd48b;
    border-radius: 2px;
    background: rgba(0, 0, 0, 0);
}
/deee/.el-checkbox__inner::after {
    border: 1px solid #ffd48b !important;
}
/deep/input::-webkit-input-placeholder {
    color: #7b7059;
}
.denglu {
    width: 214px;
    height: 32px;
    background: linear-gradient(180deg, #cdad5f, #f2ead1) !important;
    border: 0px;
    border-radius: 2px;
    font-size: 16px;
    font-family: '微软雅黑';
    font-weight: 400;
    text-align: center;
    color: #0b0404;
    letter-spacing: 3.2px;
    margin-top: 47px;
    line-height: 32px;
    padding: 0px !important;
}
.ljzhuche {
    width: 214px;
    text-align: center;
    padding-top: 10px;
    color: #ffb331;
    font-family: '微软雅黑';
    &:hover {
        color: #ffd48b;
    }
}
/deep/input::-webkit-input-placeholder {
    font-weight: 400;
    text-align: left;
    color: #978152;
    font-family: '微软雅黑';
}
</style>
